﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SocialShare.BusinessLogicLayer;
using SocialShare.BusinessEntities;
using SocialShare.DAL.Facades;
using SocialShare.BLL;
using System.Configuration;
using Utilities;
using Imgalib.Utility;

namespace SocialShare.Web
{
    public partial class signin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {               
                String returnUrl =HttpContext.Current.Request.QueryString["ReturnUrl"];
                if (!String.IsNullOrEmpty(returnUrl))
                {
                    if (HttpContext.Current.Request.QueryString["ReturnUrl"].ToLower().Contains("admin"))
                    {
                        HttpContext.Current.Response.Redirect("~/admin-login.aspx?ReturnUrl=" + HttpContext.Current.Request.QueryString["ReturnUrl"]);
                    }
                }
                else
                {
                    LoadHTML5Types();
                }
            }
        }

        private void LoadHTML5Types()
        {
            txtEmail.Attributes["type"] = "email";
            txtUserName.Attributes["type"] = "email";
            txtPassword.Attributes["type"] = "password";
        }

        protected void btnRegister_Click(object sender, EventArgs e)
        {
            ConfigReader configReader = new ConfigReader();
            SocialShare_Members member = new SocialShare_Members();
            member.CreateDate = DateTime.Now;
            member.Email = txtEmail.Value.Trim();
            member.ScreenName = txtName.Value.Trim();
            member.AuthCode = Guid.NewGuid().ToString();
            member.AccountStatus = (Int32)MEMBER_STATUS.InActive;

            SocialShare_MemberProfiles profile = new SocialShare_MemberProfiles();
            profile.BlogName = member.ScreenName;
            

            MemberFacade memberFacade = new MemberFacade();
            
            if(memberFacade.GetMemberByScreenName(txtName.Value.Trim())!=null)
            {
                divMessage.Attributes.Add("class", "error");
                lblMessage.Text = configReader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.MessageLocation.ToString()], SITE_MESSAGES.SCREEN_NAME_EXISTS.ToString());

            }

            if (memberFacade.GetMemberByUserName(txtEmail.Value.Trim()) != null)
            {
                divMessage.Attributes.Add("class", "error");
                lblMessage.Text = configReader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.MessageLocation.ToString()], SITE_MESSAGES.EMAIL_EXISTS.ToString());

            }
            else
            {
                Int32 memberId = memberFacade.CreateNewMember(member);
                if (memberId > 0)
                {
                    profile.UserId = memberId.ToString();
                    memberFacade.CreateNewMemberProfile(profile);

                    SendRegistrationEmail(member.AuthCode, member);
                    divMessage.Attributes.Add("class", "success");
                    lblMessage.Text = configReader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.MessageLocation.ToString()], SITE_MESSAGES.REGISTRATION_SUCCESS.ToString());
                }
                else
                {
                    divMessage.Attributes.Add("class", "error");
                    lblMessage.Text = configReader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.MessageLocation.ToString()], SITE_MESSAGES.REGISTRATION_FAILED.ToString());
                }
            }
        }

        private void SendFBRegistrationEmail(String authCode, SocialShare_Members member)
        {
            ConfigReader reader = new ConfigReader();
            String errMsg = String.Empty;
            String adminEmail = reader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.SiteConfigLocation.ToString()], SITE_CONFIG.ADMIN_EMAIL.ToString());
            String siteName = reader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.SiteConfigLocation.ToString()], SITE_CONFIG.SITE_NAME.ToString());

            String mailTemplate = reader.ReadEmailTemplate(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.FBRegEmail.ToString()]);
            String approvalLocation = Utilities.SiteSettings.BaseUrl + "signin.aspx";
            mailTemplate = mailTemplate.Replace("<%%URL%%>", approvalLocation);
            mailTemplate = mailTemplate.Replace("<%%ACTIVATION_CODE%%>", authCode);
            Emailer emailer = new Emailer();
            emailer.SMTP_HOST = reader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.SiteConfigLocation.ToString()], SITE_CONFIG.SMTP_HOST.ToString());
            emailer.SMTP_USER_NAME = reader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.SiteConfigLocation.ToString()], SITE_CONFIG.SMTP_USER_NAME.ToString());
            emailer.SMTP_PASSWORD = reader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.SiteConfigLocation.ToString()], SITE_CONFIG.SMTP_PASSWORD.ToString());
            emailer.SendMail(member.Email, adminEmail, siteName, "Activate your socialshare account", mailTemplate, ref errMsg);
        }

        private void SendRegistrationEmail(String authCode, SocialShare_Members member)
        {
            ConfigReader reader = new ConfigReader();
            String errMsg = String.Empty;
            String adminEmail=reader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.SiteConfigLocation.ToString()], SITE_CONFIG.ADMIN_EMAIL.ToString());
            String siteName = reader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.SiteConfigLocation.ToString()], SITE_CONFIG.SITE_NAME.ToString());

            String mailTemplate = reader.ReadEmailTemplate(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.RegistrationEmailTemplate.ToString()]);
            String approvalLocation=Utilities.SiteSettings.BaseUrl + "activate-account.aspx";
            mailTemplate = mailTemplate.Replace("<%%URL%%>", approvalLocation);
            mailTemplate = mailTemplate.Replace("<%%ACTIVATION_CODE%%>", authCode);
            Emailer emailer=new Emailer();
            emailer.SMTP_HOST = reader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.SiteConfigLocation.ToString()], SITE_CONFIG.SMTP_HOST.ToString());
            emailer.SMTP_USER_NAME = reader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.SiteConfigLocation.ToString()], SITE_CONFIG.SMTP_USER_NAME.ToString());
            emailer.SMTP_PASSWORD = reader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.SiteConfigLocation.ToString()], SITE_CONFIG.SMTP_PASSWORD.ToString());
            emailer.SendMail(member.Email, adminEmail, siteName, "Activate your socialshare account", mailTemplate, ref errMsg);
        }

        protected void btnSignIn_Click(object sender, EventArgs e)
        {
            ConfigReader configReader = new ConfigReader();
            MemberFacade memberFacade = new MemberFacade();
            SocialShare_Members member = memberFacade.ValidateUser(txtUserName.Value.Trim(), txtPassword.Value.Trim());
            if (member == null)
            {
                divMessage.Attributes.Add("class", "error");
                lblMessage.Text = configReader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.MessageLocation.ToString()], SITE_MESSAGES.PASSWORD_NOT_MATCHED.ToString());
            }
            else
            {               
                HttpCookie cookie = System.Web.Security.FormsAuthentication.GetAuthCookie(txtUserName.Value.Trim(), true);
                // Extract the ticket
                System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(cookie.Value);
                // Create the new identity for this request
                System.Web.Security.FormsIdentity identity = new System.Web.Security.FormsIdentity(ticket);
                // Apply it.
                Context.User = new System.Security.Principal.GenericPrincipal(identity, null);
                Context.Response.Cookies.Add(cookie);
                SessionManager.LOGGED_IN_USER_ID = member.Member_Id.ToString();
                CookieManager.LOGGED_IN_USER_ID = member.Member_Id.ToString();
                SessionManager.LOGGED_IN_USER_NAME = String.Format("{0}", member.ScreenName);
                System.Web.Security.FormsAuthentication.RedirectFromLoginPage(txtUserName.Value.Trim(), chkRememberMe.Checked);
                if (HttpContext.Current.Request.QueryString["ReturnUrl"]!=null && !String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ReturnUrl"].ToLower()))
                {
                    HttpContext.Current.Response.Redirect(HttpContext.Current.Request.QueryString["ReturnUrl"]);
                }
                else
                {
                    HttpContext.Current.Response.Redirect("~/my-account/default.aspx");
                }
            }
        }

        /// <summary>
        /// FB connect Registration
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRegFB_Click(object sender, EventArgs e)
        {
            ConfigReader configReader = new ConfigReader();
            SocialShare_Members member = new SocialShare_Members();
            member.CreateDate = DateTime.Now;
            member.Email = hidEmail.Value.Trim();
            member.ScreenName = hidUserName.Value.Trim();
            member.AccountStatus = (Int32)MEMBER_STATUS.Active;
            member.AuthCode = hidUID.Value.ToString();

            SocialShare_MemberProfiles profile = new SocialShare_MemberProfiles();
            profile.BlogName = member.ScreenName;

            MemberFacade memberFacade = new MemberFacade();

            if (memberFacade.GetMemberByScreenName(hidUserName.Value.Trim()) != null)
            {
                divMessage.Attributes.Add("class", "error");
                lblMessage.Text = configReader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.MessageLocation.ToString()], SITE_MESSAGES.SCREEN_NAME_EXISTS.ToString());

            }

            if (memberFacade.GetMemberByUserName(hidEmail.Value.Trim()) != null)
            {
                divMessage.Attributes.Add("class", "error");
                lblMessage.Text = configReader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.MessageLocation.ToString()], SITE_MESSAGES.EMAIL_EXISTS.ToString());

            }
            else
            {
                Int32 memberId = memberFacade.CreateNewMember(member);
                if (memberId > 0)
                {
                    profile.UserId = memberId.ToString();
                    memberFacade.CreateNewMemberProfile(profile);
                    SendFBRegistrationEmail(member.AuthCode, member);
                    divMessage.Attributes.Add("class", "success");
                    lblMessage.Text = configReader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.MessageLocation.ToString()], SITE_MESSAGES.REGISTRATION_SUCCESS.ToString());
                }
                else
                {
                    divMessage.Attributes.Add("class", "error");
                    lblMessage.Text = configReader.ReadConfigurationValue(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.MessageLocation.ToString()], SITE_MESSAGES.REGISTRATION_FAILED.ToString());
                }
            }
        }
    }
}